package netty.test13GroupChat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class GroupChatClient {
    //相关属性
    private final String host;
    private final int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }


    public void run() throws InterruptedException {


        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //1,得到pipleLine
                            ChannelPipeline pipeline = ch.pipeline();
                            //向pipleLine里加入一个解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            // 向pipleLine 里加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            //客户端加入自己的 handler
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.connect(host, port).sync();
            //客户端自己拿到channel做一些操作输入数据等（客户端收消息是在单独的 handler（GroupChatClientHandler）中处理）
            Channel channel = sync.channel();
            System.out.println("客户端准备好了---"+channel.localAddress());
            //这里我们创建一个扫描器，用于从控制台输入数据
            Scanner scanner=new Scanner(System.in);
            while(scanner.hasNextLine()){//如果还有下一行（循环读取）
                String msg = scanner.nextLine();
                //通过channel 发送的服务器端
                channel.writeAndFlush(msg+"\r\n");
            }

        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatClient("127.0.0.1",7000).run();
    }
}
